//
//  MNDPlusRecordViewController.m
//  PlusTenderDemo
//
//  Created by Vitas on 2018/7/18.
//  Copyright © 2018年 Bylongma. All rights reserved.
//

#import "MNDPlusRecordViewController.h"
#import "MNDPlusRecordDetailViewController.h"
#import "MNDPlusRecordListCell.h"
#import "SYRefreshControl.h"
#import "MNDPlusRecordModel.h"

@interface MNDPlusRecordViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic, assign) NSInteger perpage;

@property(nonatomic, strong) NSMutableArray *dataArray;
@property(nonatomic, assign) NSInteger totalNum;

@end

@implementation MNDPlusRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    kdeclare_weakself
    [SYRefreshControl configGifMJRefresh:self.tableView
                             refreshType:MJRefreshSupportALl
                            beginRefresh:YES
                         timeLabelHidden:YES
                        stateLabelHidden:YES
                            refreshBlock:^{
                                
                                [weakSelf loadDatas];
                                
                            } loadMoreBlock:^{
                                
                                [weakSelf loadMoreDatas];
                            }];
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goInvestButtonAction:) name:@"goInvestButtonAction" object:nil];

    // Do any additional setup after loading the view.
}

- (void)goInvestButtonAction:(NSNotification *)notification {
    self.tabBarController.selectedIndex = 1;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"GoTenderActionNotification" object:@0];
    [self.navigationController popToRootViewControllerAnimated:YES];
}



#pragma mark - 懒加载
- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

#pragma mark - 加载数据
- (void)loadDatas {
    
    kdeclare_weakself;
    self.perpage = 1;
    NSDictionary *params = @{
                             @"perpage": @(self.perpage),
                             @"pagesize":@(10),
                             @"sign_status":_isExit==YES ? @(2) : @(1)
                             };
    [APIManager sendRequestWithURL:API_AUTO_PLUS_BORROW_RECORD parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            weakSelf.dataArray = [MNDPlusRecordModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"user_tender_plan"]];
            weakSelf.totalNum = [responseModel.data[@"total_rows"] integerValue];
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:weakSelf.dataArray.count];
            [weakSelf.view configBlankPage:SYBlankPageTypeNoData hasData:weakSelf.dataArray.count reloadButtonBlock:nil];
            if(weakSelf.dataArray.count <= 0) {
                weakSelf.view.blankPageView.investButton.hidden = NO;
            }
            [weakSelf.tableView reloadData];
        }else {
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
        if (weakSelf.dataArray.count > 0) {
            [NetworkProgressHUD showHudNetworkError:error];
        } else {
            SYBlankPageType blankType = [weakSelf.view blankPageTypeWithError:error];
            [weakSelf.view configBlankPage:blankType
                                   hasData:NO
                         reloadButtonBlock:^(id sender) {
                             [weakSelf loadDatas];
                         }];
        }
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}


- (void)loadMoreDatas {
    
    kdeclare_weakself;
    self.perpage ++;
    NSDictionary *params = @{
                             @"perpage": @(self.perpage),
                             @"pagesize":@(10),
                             @"sign_status":_isExit==YES ? @(2) : @(1)
                             };
    [APIManager sendRequestWithURL:API_AUTO_PLUS_BORROW_RECORD parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            NSArray *array = [MNDPlusRecordModel mj_objectArrayWithKeyValuesArray:responseModel.data[@"user_tender_plan"]];
            [weakSelf.dataArray addObjectsFromArray:array];
            [weakSelf.tableView reloadData];
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:array.count];
            
        }else {
            [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [SYRefreshControl configAfterLoading:weakSelf.tableView hasData:NO];
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MNDPlusRecordModel *model = self.dataArray[indexPath.row];
    MNDPlusRecordListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MNDPlusRecordListCell"];
    cell.isExit = self.isExit;
    cell.recordModel = model;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    MNDPlusRecordModel *model = self.dataArray[indexPath.row];
    MNDPlusRecordDetailViewController *detailVC = [UIStoryboard viewControllerWithIdentifier:@"MNDPlusRecordDetailViewController"];
    detailVC.title = model.plan_title;
    detailVC.sign_id = model.sign_id;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetY = scrollView.contentOffset.y;
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(plusRecordListScroll: withTotalNum:)]) {
        [self.delegate plusRecordListScroll:scrollView withTotalNum:self.totalNum];
    }
    NSLog(@"offsetY = %lf",offsetY);
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
